<template>
  <el-card>
    <h2>开业设置门店提交</h2>
    <el-table :data="storeList" style="width: 100%">
      <el-table-column prop="store.storeName" label="门店名称" />
      <el-table-column label="提交人">
        <template #default="{ row }">
          {{ getEmployee1Name(row.store.employee1Id) }}
        </template>
      </el-table-column>
      <el-table-column label="操作时间">
        <template #default="{ row }">
          {{ formatDateTime(row.employeeType1PhotosCreateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="goDetail(row.store.storeId)">开业设置</el-button>
          <el-button type="danger" size="small" @click="onReject(row.store.storeId)">驳回</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        @current-change="handlePageChange"
        layout="total, prev, pager, next"
        style="margin-top: 16px;"
    />
    <h3 style="margin-top:32px;">待开业门店</h3>
    <el-table :data="openedList" style="width: 100%">
      <el-table-column prop="store.storeName" label="门店名称" />
      <el-table-column label="提交人">
        <template #default="{ row }">
          {{ getEmployee2Name(row.store.employee2Id) }}
        </template>
      </el-table-column>
      <el-table-column label="开业时间">
        <template #default="{ row }">
          {{ formatDateTime(row.store.openingDate) || '无' }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }">
          <span v-if="row.store.openingDate && isToday(row.store.openingDate)">今日开业</span>
          <span v-else-if="row.store.openingDate && new Date(row.store.openingDate) < new Date().setHours(0,0,0,0)">已开业</span>
          <span v-else>待开业</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button size="small" @click="viewOpened(row.store.storeId)">查看详情</el-button>
          <el-button type="warning" size="small" :disabled="!canConfirmOpening(row)" @click="onReceived(row.store)" style="margin-left: 4px;">确认开业</el-button>
          <el-button type="success" size="small" @click="showStoreHandover(row.store)" style="margin-left: 4px;">门店交接</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="openedPageNum"
        :page-size="openedPageSize"
        :total="openedTotal"
        @current-change="handleOpenedPageChange"
        layout="total, prev, pager, next"
        style="margin-top: 16px;"
    />
    <h3 style="margin-top:32px;">待交接门店</h3>
    <el-table :data="handoverList" style="width: 100%">
      <el-table-column prop="store.storeName" label="门店名称" />
      <el-table-column label="提交人">
        <template #default="{ row }">
          {{ getEmployee2Name(row.store.employee2Id) }}
        </template>
      </el-table-column>
      <el-table-column label="开业时间">
        <template #default="{ row }">
          {{ formatDateTime(row.store.openingDate) || '无' }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default>待交接</template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="success" size="small" @click="showHandover(row.store.storeId)" style="margin-left: 4px;">老店交接</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="handoverPageNum"
        :page-size="handoverPageSize"
        :total="handoverTotal"
        @current-change="handleHandoverPageChange"
        layout="total, prev, pager, next"
        style="margin-top: 16px;"
    />
    <!-- 新增：已交接门店模块 -->
    <h3 style="margin-top:32px;">已交接门店</h3>
    <el-table :data="finishedList" style="width: 100%">
      <el-table-column prop="store.storeName" label="门店名称" />
      <el-table-column label="提交人">
        <template #default="{ row }">
          {{ row.handover?.submitter || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="交接时间">
        <template #default="{ row }">
          {{ row.handover?.submitTime ? formatDateOnly(row.handover.submitTime) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="small" @click="viewHandoverDetail(row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="finishedPageNum"
        :page-size="finishedPageSize"
        :total="finishedTotal"
        @current-change="handleFinishedPageChange"
        layout="total, prev, pager, next"
        style="margin-top: 16px;"
    />
    <el-dialog v-model="dialogVisible" title="开业详情" width="600px">
      <div v-if="openedDetail">
        <div style="margin-bottom:12px;"><b>开业时间：</b>{{ formatDateTime(openedDetail.openingDate) || '无' }}</div>
        <div style="margin-bottom:12px;"><b>培训证明：</b>
          <img v-if="openedDetail.trainingImage" :src="openedDetail.trainingImage" style="max-width:400px;max-height:200px;" />
          <span v-else>无</span>
        </div>
      </div>
      <div v-else>加载中...</div>
    </el-dialog>
    <el-dialog v-model="todayDialogVisible" title="今日开店提醒" width="500px" class="remind-dialog">
      <div v-if="todayOpening.count > 0" class="remind-content">
        <el-alert type="success" :closable="false" show-icon class="remind-alert">
          <template #icon>
            <el-icon><BellFilled /></el-icon>
          </template>
          <span class="remind-title">今日有门店开业，请及时关注！</span>
        </el-alert>
        <div class="remind-count">
          今日开店数量：<span class="highlight">{{ todayOpening.count }}</span>
        </div>
        <el-divider content-position="left">开业门店列表</el-divider>
        <ul class="store-list">
          <li v-for="(item, idx) in todayOpening.list" :key="item.storeId" class="store-item">
            <div class="store-info">
              <span class="store-index">{{ idx + 1 }}.</span>
              <span class="store-name">{{ item.storeName }}</span>
              <span class="store-date">({{ formatDateTime(item.openingDate) }})</span>
            </div>
            <el-button type="warning" size="small" class="received-btn" @click="onReceived(item)">收到</el-button>
          </li>
        </ul>
      </div>
      <div v-else class="remind-empty">
        <el-icon class="remind-empty-icon"><BellFilled /></el-icon>
        <div class="remind-empty-text">今日无开店门店</div>
      </div>
      <template #footer>
        <el-button type="primary" @click="todayDialogVisible = false">确认</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="handoverDialogVisible" title="老店交接" width="500px">
      <el-form :model="handoverForm" :rules="handoverRules" ref="handoverFormRef" label-width="100px">
        <el-form-item label="提交人" prop="submitter">
          <el-input v-model="handoverForm.submitter" placeholder="请输入提交人姓名" />
        </el-form-item>
        <el-form-item label="接手人" prop="receiver">
          <el-select v-model="handoverForm.receiver" placeholder="请选择接手人">
            <el-option v-for="emp in employee4List" :key="emp.employeeId" :label="emp.name" :value="emp.account" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间" prop="submitTime">
          <el-input v-model="handoverForm.submitTime" placeholder="自动获取当前时间" readonly style="width: 100%;" />
        </el-form-item>
        <el-form-item label="提交备注" prop="remark">
          <el-input
              v-model="handoverForm.remark"
              type="textarea"
              :rows="4"
              placeholder="请输入交接备注信息"
          />
        </el-form-item>
        <!-- 新增：上传图片功能，可多选可不传 -->
                 <el-form-item label="交接照片">
           <UploadImage v-model="handoverForm.photoArr" :multiple="true" :limit="6" uploadUrl="http://121.43.176.9:8090/api/oss/upload-image" />
         </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handoverDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitHandover" :loading="handoverSubmitting">
          {{ handoverSubmitting ? '提交中...' : '提交' }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="handoverDetailDialogVisible" title="交接详情" width="600px">
      <div v-if="handoverDetail && handoverDetail.handoverList && handoverDetail.handoverList.length">
        <div style="margin-bottom:12px;"><b>提交人：</b>{{ handoverDetail.handoverList[0].submitter }}</div>
        <div style="margin-bottom:12px;"><b>提交时间：</b>{{ formatDateTime(handoverDetail.handoverList[0].submitTime) }}</div>
        <div style="margin-bottom:12px;"><b>接收人：</b>{{ handoverDetail.handoverList[0].receiver }}</div>
        <div style="margin-bottom:12px;"><b>备注：</b>{{ handoverDetail.handoverList[0].remarks }}</div>
        <div style="margin-bottom:12px;"><b>交接照片：</b>
          <template v-if="handoverDetail.handoverList[0].photo">
            <el-image v-for="(url, idx) in handoverDetail.handoverList[0].photo.split(',')" :key="idx" :src="url" style="width:80px;height:80px;margin-right:8px;" :preview-src-list="handoverDetail.handoverList[0].photo.split(',')" :initial-index="idx" fit="cover" />
          </template>
          <span v-else>无</span>
        </div>
      </div>
      <div v-else>暂无数据</div>
      <template #footer>
        <el-button @click="handoverDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    
    <!-- 门店交接弹窗 -->
    <el-dialog v-model="storeHandoverDialogVisible" title="门店交接" width="400px">
      <div class="store-handover-content">
        <el-form :model="storeHandoverForm" label-width="100px">
          <el-form-item label="门店名称">
            <el-input v-model="storeHandoverForm.storeName" readonly />
          </el-form-item>
          <el-form-item label="选择交接人" required>
            <el-select 
              v-model="storeHandoverForm.employee2Id" 
              placeholder="请选择交接人"
              style="width: 100%;"
              filterable
            >
              <el-option 
                v-for="employee in employee2List" 
                :key="employee.employeeId" 
                :label="`${employee.name} (${employee.account})`" 
                :value="employee.employeeId"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="store-handover-footer">
          <el-button @click="storeHandoverDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStoreHandover" :loading="isStoreHandovering">
            {{ isStoreHandovering ? '交接中...' : '确认交接' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatDateTime, formatDate } from '../utils/dateUtils';
import { useUserStore } from '@/store/user';
import { BellFilled } from '@element-plus/icons-vue';
import UploadImage from '@/components/UploadImage.vue';

// 格式化日期，只显示日期不显示时分秒
function formatDateOnly(dateStr) {
  if (!dateStr) return '-';
  try {
    const date = new Date(dateStr);
    return date.toISOString().split('T')[0]; // 只返回 YYYY-MM-DD 格式
  } catch (error) {
    return '-';
  }
}

// 获取交接时间的数值，用于排序
function getHandoverTimeValue(row) {
  if (!row.handover || !row.handover.submitTime) {
    return 0; // 如果没有交接时间，排在最后
  }
  
  try {
    return new Date(row.handover.submitTime).getTime();
  } catch (error) {
    console.error('解析交接时间失败:', error);
    return 0;
  }
}

const userStore = useUserStore();
const storeList = ref([]);
const pageNum = ref(1);
const pageSize = ref(5);
const total = ref(0);
const openedList = ref([]);
const openedPageNum = ref(1);
const openedPageSize = ref(5);
const openedTotal = ref(0);
const handoverList = ref([]);
const handoverPageNum = ref(1);
const handoverPageSize = ref(5);
const handoverTotal = ref(0);
const finishedList = ref([]);
const finishedPageNum = ref(1);
const finishedPageSize = ref(5);
const finishedTotal = ref(0);
const router = useRouter();
const dialogVisible = ref(false);
const openedDetail = ref(null);
const todayDialogVisible = ref(false);
const todayOpening = ref({ count: 0, list: [] });
const employee1List = ref([]);
const employee2List = ref([]);
const handoverDialogVisible = ref(false);
const handoverFormRef = ref();
const handoverSubmitting = ref(false);
const currentHandoverStoreId = ref(null);
const handoverForm = ref({
  submitter: '',
  receiver: '',
  submitTime: null,
  remark: '',
  photoArr: [],
  storeName: '' // 新增
});
const handoverRules = {
  submitter: [
    { required: true, message: '请输入提交人姓名', trigger: 'blur' }
  ],
  receiver: [
    { required: true, message: '请选择接手人', trigger: 'change' }
  ],
  remark: [
    { required: true, message: '请输入提交备注', trigger: 'blur' }
  ]
};
const handoverDetailDialogVisible = ref(false);
const handoverDetail = ref(null);
const employee4List = ref([]); // permission_type=4员工列表

// 门店交接相关
const storeHandoverDialogVisible = ref(false);
const storeHandoverForm = ref({
  storeId: null,
  storeName: '',
  employee2Id: null
});
const isStoreHandovering = ref(false);

async function fetchList() {
  // 1. 待开业门店（分页）
  const res1 = await fetch(`http://121.43.176.9:8090/api/store/pending2?pageNum=${pageNum.value}&pageSize=${pageSize.value}`).then(r => r.json());
  if (res1.code === 200 && res1.data) {
    storeList.value = res1.data.records;
    total.value = res1.data.total;
  } else {
    storeList.value = [];
    total.value = 0;
  }

  // 2. 状态3/4门店（根据员工角色使用不同接口）
  let url3to4;
  if (Number(userStore.roleCode) === 3) {
    // 管理员：使用原有接口
    url3to4 = 'http://121.43.176.9:8090/api/store/status3to4';
  } else if (Number(userStore.roleCode) === 2) {
    // 员工2：使用新接口，获取分配给该员工2的门店
    url3to4 = `http://121.43.176.9:8090/api/store/status3to4-by-employee2?employee2Id=${userStore.userId}`;
  } else {
    // 其他员工：使用原有接口
    url3to4 = 'http://121.43.176.9:8090/api/store/status3to4';
    if (Number(userStore.roleCode) !== 3) {
      url3to4 += `?createUserId=${userStore.userId}`;
    }
  }

  const res3to4 = await fetch(url3to4).then(r => r.json());
  let all3to4 = [];
  if (res3to4.code === 200 && res3to4.data) {
    if (Array.isArray(res3to4.data)) {
      all3to4 = res3to4.data;
    } else if (res3to4.data.records) {
      all3to4 = res3to4.data.records;
    } else if (res3to4.data.list) {
      all3to4 = res3to4.data.list;
    }
  }
  // 待开业（status=3）
  const openedRaw = all3to4.filter(item => item.store && item.store.status === 3);
  openedTotal.value = openedRaw.length;
  const oStart = (openedPageNum.value - 1) * openedPageSize.value;
  const oEnd = oStart + openedPageSize.value;
  openedList.value = openedRaw.slice(oStart, oEnd);

  // 待交接（status=4）
  const handoverRaw = all3to4.filter(item => item.store && item.store.status === 4);
  handoverTotal.value = handoverRaw.length;
  const hStart = (handoverPageNum.value - 1) * handoverPageSize.value;
  const hEnd = hStart + handoverPageSize.value;
  handoverList.value = handoverRaw.slice(hStart, hEnd);

  // 3. 已交接门店（status=5，前端分页）
  let url5;
  if (Number(userStore.roleCode) === 3) {
    // 管理员：使用原有接口
    url5 = 'http://121.43.176.9:8090/api/store/status5';
  } else if (Number(userStore.roleCode) === 2) {
    // 员工2：使用新接口，获取分配给该员工2的门店
    url5 = `http://121.43.176.9:8090/api/store/status5-by-employee2?employee2Id=${userStore.userId}`;
  } else {
    // 其他员工：使用原有接口
    url5 = 'http://121.43.176.9:8090/api/store/status5';
    if (Number(userStore.roleCode) !== 3) {
      url5 += `?createUserId=${userStore.userId}`;
    }
  }

  const res5 = await fetch(url5).then(r => r.json());
  let all5 = [];
  if (res5.code === 200 && res5.data) {
    if (Array.isArray(res5.data)) {
      all5 = res5.data;
    } else if (res5.data.records) {
      all5 = res5.data.records;
    } else if (res5.data.list) {
      all5 = res5.data.list;
    }
  }
  
  // 为每个已交接门店获取交接详情
  const finishedWithHandover = [];
  for (const item of all5) {
    const storeId = item.store?.storeId || item.storeId;
    if (storeId) {
      try {
        const handoverRes = await fetch(`http://121.43.176.9:8090/api/store-handover/detail/by-store/${storeId}`).then(r => r.json());
        if (handoverRes.code === 200 && handoverRes.data && handoverRes.data.handoverList && handoverRes.data.handoverList.length > 0) {
          const handoverInfo = handoverRes.data.handoverList[0];
          finishedWithHandover.push({
            ...item,
            handover: {
              submitter: handoverInfo.submitter || '-',
              submitTime: handoverInfo.submitTime
            }
          });
        } else {
          // 如果没有交接详情，使用默认值
          finishedWithHandover.push({
            ...item,
            handover: {
              submitter: '-',
              submitTime: null
            }
          });
        }
      } catch (error) {
        console.error('获取交接详情失败:', error);
        // 出错时使用默认值
        finishedWithHandover.push({
          ...item,
          handover: {
            submitter: '-',
            submitTime: null
          }
        });
      }
    } else {
      finishedWithHandover.push({
        ...item,
        handover: {
          submitter: '-',
          submitTime: null
        }
      });
    }
  }
  
  // 按交接时间排序，时间越靠后的排在越前面
  finishedWithHandover.sort((a, b) => {
    const timeA = getHandoverTimeValue(a);
    const timeB = getHandoverTimeValue(b);
    return timeB - timeA; // 降序排列，最新的在前
  });
  
  finishedTotal.value = finishedWithHandover.length;
  const fStart = (finishedPageNum.value - 1) * finishedPageSize.value;
  const fEnd = fStart + finishedPageSize.value;
  finishedList.value = finishedWithHandover.slice(fStart, fEnd);
}

function handlePageChange(val) {
  pageNum.value = val;
  fetchList();
}
function handleOpenedPageChange(val) {
  openedPageNum.value = val;
  fetchList();
}
function handleHandoverPageChange(val) {
  handoverPageNum.value = val;
  fetchList();
}
function handleFinishedPageChange(val) {
  finishedPageNum.value = val;
  fetchList();
}
function goDetail(storeId) {
  router.push(`/employee/type2/${storeId}`);
}
async function viewOpened(storeId) {
  dialogVisible.value = true;
  openedDetail.value = null;
  // 获取员工2开业提交数据
  const res = await fetch(`http://121.43.176.9:8090/api/employee/type2/opening?storeId=${storeId}`).then(r => r.json());
  if (res.code === 200 && res.data) {
    openedDetail.value = res.data;
  } else {
    openedDetail.value = {};
    ElMessage.error(res.msg || '未找到开业数据');
  }
}
async function fetchTodayOpening() {
  try {
    const res = await fetch('http://121.43.176.9:8090/api/store/remind', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userId: userStore.userId })
    }).then(r => r.json());
    if (res.code === 200 && res.data) {
      todayOpening.value = {
        count: res.data.total,
        list: res.data.list
      };
      todayDialogVisible.value = true;
    }
  } catch (e) {
    ElMessage.error('今日开店数据加载失败');
  }
}
async function onReject(storeId) {
  ElMessageBox.confirm('确定要驳回该门店吗？', '提示', { type: 'warning' })
      .then(async () => {
        // 调用后端接口，status=1，employee2Id=null
        const res = await fetch(`http://121.43.176.9:8090/api/store/reject`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ storeId })
        }).then(r => r.json());
        if (res.code === 200) {
          ElMessage.success('已驳回');
          fetchList();
        } else {
          ElMessage.error(res.msg || '驳回失败');
        }
      });
}
function onEdit(storeId) {
  router.push(`/employee/type2/${storeId}?edit=1`);
}
function getEmployee1Name(id) {
  const emp = employee1List.value.find(e => e.employeeId === id);
  return emp ? emp.name : id || '-';
}
function getEmployee2Name(id) {
  const emp = employee2List.value.find(e => e.employeeId === id);
  return emp ? emp.name : id || '-';
}
function showHandover(storeId) {
  currentHandoverStoreId.value = storeId;
  // 从 handoverList 查找 storeName
  let storeName = '';
  const storeObj = handoverList.value.find(item => item.store && item.store.storeId === storeId);
  if (storeObj && storeObj.store && storeObj.store.storeName) {
    storeName = storeObj.store.storeName;
  }
  
  // 获取当前本地时间的年月日时分秒格式
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  
  handoverForm.value = {
    submitter: '',
    receiver: '',
    submitTime: currentTime,
    remark: '',
    photoArr: [],
    storeName // 新增
  };
  handoverDialogVisible.value = true;
}
async function submitHandover() {
  if (handoverSubmitting.value) {
    ElMessage.warning('正在提交中，请稍候...');
    return;
  }
  try {
    await handoverFormRef.value.validate();
  } catch (err) {
    const firstError = Object.values(err)[0]?.[0]?.message;
    if (firstError) {
      ElMessage.error(firstError);
    }
    return;
  }
  handoverSubmitting.value = true;
  try {
    // 新增：处理图片URL数组为逗号分隔字符串
    const photoUrls = (handoverForm.value.photoArr || []).map(f => f.url).filter(Boolean);
    const dto = {
      storeId: currentHandoverStoreId.value,
      storeName: handoverForm.value.storeName, // 新增
      submitter: handoverForm.value.submitter,
      receiver: handoverForm.value.receiver,
      submitTime: handoverForm.value.submitTime,
      remarks: handoverForm.value.remark,
      photo: photoUrls.join(',')
    };
    const res = await fetch('http://121.43.176.9:8090/api/store/associate', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(dto)
    }).then(r => r.json());
    if (res.code === 200) {
      ElMessage.success('老店交接提交成功');
      handoverDialogVisible.value = false;
      fetchList(); // 刷新列表
      
      // 新增：调用/api/log/add接口，传入stage: 6
      const log = {
        storeId: currentHandoverStoreId.value,
        relatedId: currentHandoverStoreId.value,
        submitFrom: userStore.userId + ':' + (userStore.userName || ''),
        submitTo: handoverForm.value.receiver || '-',
        submitTime: new Date().toISOString(),
        relatedType: 'store',
        stage: 6
      };
      await fetch('http://121.43.176.9:8090/api/log/add', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(log)
      });
    } else {
      ElMessage.error(res.msg || '提交失败');
    }
  } catch (error) {
    ElMessage.error('提交失败: ' + error.message);
  } finally {
    handoverSubmitting.value = false;
  }
}
async function fetchEmployee1List() {
  const res = await fetch('http://121.43.176.9:8090/api/employee/type1/list').then(r => r.json());
  if (res.code === 200) {
    employee1List.value = res.data;
  } else {
    employee1List.value = [];
  }
}
async function fetchEmployee2List() {
  const res = await fetch('http://121.43.176.9:8090/api/employee/type2/list').then(r => r.json());
  if (res.code === 200) {
    employee2List.value = res.data;
  } else {
    employee2List.value = [];
  }
}
async function onReceived(item) {
  try {
    const res = await fetch('http://121.43.176.9:8090/api/store/confirm-reminder', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ storeId: item.storeId })
    }).then(r => r.json());
    if (res.code === 200) {
      ElMessage.success(`已收到门店【${item.storeName}】的开业提醒`);
      // 移除已收到的门店
      todayOpening.value.list = todayOpening.value.list.filter(store => store.storeId !== item.storeId);
      todayOpening.value.count = todayOpening.value.count - 1;
      if (item && item.storeName !== undefined) {
        // 只有确认开业按钮（row.store）时刷新列表
        fetchList();
      }
      
      // 新增：调用/api/log/add接口，传入stage: 5
      const log = {
        storeId: item.storeId,
        relatedId: item.storeId,
        submitFrom: userStore.userId + ':' + (userStore.userName || ''),
        submitTo: '-',
        submitTime: new Date().toISOString(),
        relatedType: 'store',
        stage: 5
      };
      await fetch('http://121.43.176.9:8090/api/log/add', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(log)
      });
    } else {
      ElMessage.error(res.msg || '操作失败');
    }
  } catch (e) {
    ElMessage.error('网络错误，请稍后重试');
  }
}
function canConfirmOpening(row) {
  if (!row.store.openingDate) return false;
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const openDate = new Date(row.store.openingDate);
  openDate.setHours(0, 0, 0, 0);
  return openDate <= today;
}
function canHandover(row) {
  if (!row.store.openingDate) return false;
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const openDate = new Date(row.store.openingDate);
  openDate.setHours(0, 0, 0, 0);
  return openDate < today;
}
function isToday(dateStr) {
  if (!dateStr) return false;
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const d = new Date(dateStr);
  d.setHours(0, 0, 0, 0);
  return d.getTime() === today.getTime();
}
function canClickConfirmOpening(row) {
  return true;
}
async function viewHandoverDetail(row) {
  const storeId = row.store?.storeId || row.storeId;
  if (!storeId) {
    ElMessage.error('未找到storeId');
    return;
  }
  // 新的流程日志接口举例：/api/submission-log/query?relatedId=xxx&relatedType=store&submitType=1
  // 你可以根据需要传递 submitType
  // 这里只是举例，实际可根据业务调整
  // const logRes = await fetch(`/api/submission-log/query?relatedId=${storeId}&relatedType=store&submitType=1`).then(r => r.json());
  const res = await fetch(`http://121.43.176.9:8090/api/store-handover/detail/by-store/${storeId}`).then(r => r.json());
  if (res.code === 200 && res.data) {
    handoverDetail.value = res.data;
    handoverDetailDialogVisible.value = true;
  } else {
    ElMessage.error(res.msg || '未找到交接记录');
  }
}
onMounted(() => {
  fetchList();
  fetchTodayOpening();
  fetchEmployee1List();
  fetchEmployee2List();
  fetchEmployee4List();
});
async function fetchEmployee4List() {
  try {
    const res = await fetch('http://121.43.176.9:8090/api/employee/employee4-list').then(r => r.json());
    if (res.code === 200 && Array.isArray(res.data)) {
      employee4List.value = res.data;
    } else {
      employee4List.value = [];
    }
  } catch (e) {
    employee4List.value = [];
  }
}

// 门店交接相关方法
function showStoreHandover(store) {
  storeHandoverForm.value = {
    storeId: store.storeId,
    storeName: store.storeName,
    employee2Id: null
  };
  storeHandoverDialogVisible.value = true;
}

async function submitStoreHandover() {
  if (!storeHandoverForm.value.employee2Id) {
    ElMessage.warning('请选择交接人');
    return;
  }
  
  isStoreHandovering.value = true;
  try {
    const params = new URLSearchParams({
      storeId: storeHandoverForm.value.storeId,
      employee2Id: storeHandoverForm.value.employee2Id
    });
    
    const res = await fetch(`http://121.43.176.9:8090/api/store/update-employee2?${params.toString()}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    }).then(r => r.json());
    
    if (res.code === 200) {
      ElMessage.success('门店交接成功');
      storeHandoverDialogVisible.value = false;
      fetchList(); // 刷新列表数据
    } else {
      ElMessage.error(res.msg || '门店交接失败');
    }
  } catch (error) {
    console.error('门店交接失败:', error);
    ElMessage.error('门店交接失败，请重试');
  } finally {
    isStoreHandovering.value = false;
  }
}
</script>

<style scoped>
.remind-dialog .el-dialog__body {
  padding: 24px 32px 12px 32px;
}
.remind-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.remind-alert {
  width: 100%;
  margin-bottom: 18px;
  font-size: 16px;
  border-radius: 8px;
}
.remind-title {
  font-weight: bold;
  font-size: 18px;
  color: #409EFF;
}
.remind-count {
  font-size: 17px;
  margin-bottom: 10px;
  font-weight: 500;
  width: 100%;
  text-align: left;
}
.highlight {
  color: #f56c6c;
  font-weight: bold;
  font-size: 22px;
  margin-left: 4px;
}
.store-list {
  list-style: none;
  padding: 0;
  margin: 0;
  width: 100%;
}
.store-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f8fafd;
  border-radius: 8px;
  margin-bottom: 12px;
  padding: 12px 16px;
  box-shadow: 0 1px 4px rgba(64,158,255,0.04);
  transition: box-shadow 0.2s, background 0.2s;
}
.store-item:hover {
  background: #f0f6ff;
  box-shadow: 0 2px 8px rgba(64,158,255,0.10);
}
.store-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
}
.store-index {
  color: #409EFF;
  font-weight: bold;
}
.store-name {
  font-weight: 500;
}
.store-date {
  color: #999;
  font-size: 13px;
}
.received-btn {
  margin-left: 16px;
  min-width: 60px;
  box-shadow: 0 2px 8px rgba(255,193,7,0.10);
  font-weight: bold;
}
.received-btn:hover {
  box-shadow: 0 4px 16px rgba(255,193,7,0.18);
}
.remind-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 180px;
  color: #999;
  padding: 32px 0 24px 0;
}
.remind-empty-icon {
  font-size: 40px;
  color: #c0c4cc;
}
.remind-empty-text {
  margin-top: 14px;
  font-size: 18px;
}

.store-handover-content {
  padding: 20px 0;
}

.store-handover-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>